package 力扣日常刷题.木22二月.第14天220;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author 帅小伙
 * @date 2022/2/20
 * @description
 */
public class Demo126两个数组的交集 {


    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);

        ArrayList<Integer> ans = new ArrayList<>();
        int i = 0, j = 0;

        while (i < nums1.length && j < nums2.length) {
            int n1 = nums1[i], n2 = nums2[j];
            if (n1 == n2) {
                if (ans.size() == 0 || ans.get(ans.size() - 1) != n1) {
                    ans.add(n1);
                }
                i++;
                j++;
            } else if (n1 < n2) i++;
            else j++;
        }
        int[] res = new int[ans.size()];
        for (int k = 0; k < ans.size(); k++) {
            res[k] = ans.get(k);
        }
        return res;
    }

}
